package com.qf.game.utils;

import com.qf.game.websocket.entity.Room;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 房间管理器的工具类
 *
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class RoomManagerUtils {

    /**
     * 房间号 - 房间对象
     */
    private static Map<Integer, Room> roomsMap = new ConcurrentHashMap<>();
    /**
     * 玩家的session - 房间
     */
    private static Map<Session, Room> sessionsMap = new ConcurrentHashMap<>();

    /**
     * 添加房间
     */
    public static void addRoom(Room room){
        roomsMap.put(room.getRid(), room);
    }

    /**
     * 给当前房间设置session
     */
    public static void addRoomSession(Session session, Room room){
        sessionsMap.put(session, room);
    }

    /**
     * 根据id查询房间
     * @param rid
     * @return
     */
    public static Room getRoomById(Integer rid){
        return roomsMap.get(rid);
    }

    /**
     * 根据session获得房间信息
     * @param session
     * @return
     */
    public static Room getRoomBySession(Session session) {
        return sessionsMap.get(session);
    }

    /**
     * 根据房间id删除房间
     * @param rid
     */
    public static void removeRoom(Integer rid){
        //清除第一个map中的房间信息
        roomsMap.remove(rid);
        //清除第二个map中的房间信息
        for (Map.Entry<Session, Room> entry : new HashMap<>(sessionsMap).entrySet()) {
            if (entry.getValue().getRid().equals(rid)) {
                sessionsMap.remove(entry.getKey());
            }
        }
    }

    /**
     * 返回所有的房间信息
     * @return
     */
    public static List<Room> getRooms(){
        List resultList = roomsMap.values()
                .stream()
                .map(room -> new Room().setRid(room.getRid())
                        .setStatus(room.getStatus())
                        .setTitle(room.getTitle())
                        .setType(room.getType())
                        .setIslook(room.getIslook()))
                .collect(Collectors.toList());
        return resultList;
    }
}
